using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace CodeCounsel.SharePoint.NavigationService.Features.Farm
{
    [Guid("bb1df379-691f-4eb8-8a86-6483f0a3e3c1")]
    public class FarmEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebService adminService = (SPWebService)properties.Feature.Parent;
            SPFarm farm = adminService.Farm;
            NavigationService service = farm.Services.GetValue<NavigationService>();
            if (service == null)
            {
                service = new NavigationService(farm);
                service.Update();
                service.Provision();
            }
            NavigationServiceProxy serviceProxy = farm.ServiceProxies.GetValue<NavigationServiceProxy>();
            if (serviceProxy == null)
            {
                serviceProxy = new NavigationServiceProxy(farm);
                serviceProxy.Update();
                serviceProxy.Provision();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebService adminService = (SPWebService)properties.Feature.Parent;
            SPFarm farm = adminService.Farm;
            DeleteServiceFromFarm(farm);
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            SPWebService adminService = (SPWebService)properties.Feature.Parent;
            SPFarm farm = adminService.Farm;
            DeleteServiceFromFarm(farm);
        }

        private static void DeleteServiceFromFarm(SPFarm farm)
        {
            NavigationServiceProxy serviceProxy = farm.ServiceProxies.GetValue<NavigationServiceProxy>();
            if (serviceProxy != null)
            {
                serviceProxy.Delete();
            }
            NavigationService service = farm.Services.GetValue<NavigationService>();
            if (service != null)
            {
                service.Delete();
            }
        }
    }
}
